package com.net.oil.user;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.net.oil.R;
import com.net.oil.app.Constant;
import com.net.oil.app.UserInfoManager;
import com.net.oil.base.BaseActivity;
import com.net.oil.base.EventBussMessage;
import com.net.oil.http.AppUrl;
import com.net.oil.user.bean.UserInfo;
import com.net.oil.user.contract.UserDetailContract;
import com.net.oil.user.presenter.UserDetailPresenter;
import com.net.oil.util.DisplayUtil;
import com.net.oil.util.ImageHandle;
import com.net.oil.util.StringUtil;
import com.net.oil.util.glide.GlideUtil;
import com.net.oil.widget.ToastUtil;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class UserDetailActivity extends BaseActivity<UserDetailPresenter> implements UserDetailContract.View {

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.user_ic)
    ImageView userIc;
    @BindView(R.id.user_nick)
    TextView userNick;
    @BindView(R.id.user_phone)
    TextView userPhone;
    @BindView(R.id.user_ic_layout)
    RelativeLayout userIcLayout;
    @BindView(R.id.nick_layout)
    LinearLayout nickLayout;
    @BindView(R.id.recommend_user_phone_tv)
    TextView recommendUserPhoneTv;
    @BindView(R.id.recommend_ly)
    RelativeLayout recommendLy;

    private UserInfo userInfo;
    private UserInfo.UserDetailBean userDetail;

    private ArrayList<AlbumFile> mAlbumFiles;

    private String nick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_detail);
        ButterKnife.bind(this);
        presenter = new UserDetailPresenter(this);
        initUserInfo();
        initView();
    }

    private void initUserInfo() {
        userInfo = UserInfoManager.getInstance().getUserInfo();
        if (userInfo != null) {
            userDetail = userInfo.getUserDetail();
        }
    }

    private void initView() {
        toolbarTitle.setText("个人资料");
        toolbarGoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        if (userDetail != null) {
            if (!StringUtil.isEmpty(userDetail.getNick())) {
                userNick.setText(userDetail.getNick());
            }

            if (!StringUtil.isEmpty(userDetail.getPhone())) {
                userPhone.setText(userDetail.getPhone());
            }

            if (!StringUtil.isEmpty(userDetail.getPortrait())) {
                GlideUtil.getInstance().loadCircleImage(this, userIc, AppUrl.getImageUrl(userDetail.getPortrait()),
                        R.drawable.ic_user_default);
            }

            if (!TextUtils.isEmpty(userDetail.getInvitationPhone())) {
                recommendUserPhoneTv.setText(userDetail.getInvitationPhone());
            }
        }

    }

    @OnClick({R.id.user_ic_layout, R.id.nick_layout, R.id.recommend_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user_ic_layout:
                selectImage();
                break;
            case R.id.nick_layout:
                updateNick();
                break;
            case R.id.recommend_ly:
                recommendUserInfo();
                break;
        }
    }

    private void recommendUserInfo() {
        if (TextUtils.isEmpty(userDetail.getInvitationPhone())) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LinearLayout linearLayout = new LinearLayout(this);
            final EditText editText = new EditText(this);
            editText.setInputType(InputType.TYPE_CLASS_PHONE);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(DisplayUtil.dip2px(20), 0, DisplayUtil.dip2px(20), 0);
            editText.setLayoutParams(layoutParams);
            linearLayout.addView(editText);
            builder.setTitle("完善推荐人信息");
            builder.setView(linearLayout);

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String invitationPhone = editText.getText().toString().trim();
                    presenter.sendRecommendUserInfo(invitationPhone);
                    showProgressDialog();
                }
            });
            builder.show();
        }
    }

    private void updateNick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LinearLayout linearLayout = new LinearLayout(this);
        final EditText editText = new EditText(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(DisplayUtil.dip2px(20), 0, DisplayUtil.dip2px(20), 0);
        editText.setLayoutParams(layoutParams);
        linearLayout.addView(editText);

        editText.setFilters(new InputFilter[]{
                new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                        if (source.equals(" ")) {
                            return "";
                        }
                        return null;
                    }
                }
        });
        builder.setTitle("修改昵称");
        builder.setView(linearLayout);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                nick = editText.getText().toString().trim();
                presenter.updateNick(nick);
            }
        });
        builder.show();
    }

    /**
     * Select picture, from album.
     * 图片选择，采用的album第三方库，地址https://github.com/yanzhenjie/Album
     * 后期如果需要修改可以clone源码修改, 本项目直接采用com.yanzhenjie:album:version方式引用
     */
    private void selectImage() {
        Album.image(this)
                .multipleChoice()
                .requestCode(200)
                .camera(true)       //是否带拍照
                .columnCount(2)     //图片选择列数
                .selectCount(1)     //最大图片选择数
                .checkedList(mAlbumFiles)
                .widget(
                        Widget.newDarkBuilder(this)
                                .title("图片选择")
                                .build()
                )
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                        mAlbumFiles = result;   //选择的图片的集合
                        //选择照片成功
                        //GlideUtil.getInstance().loadImage(UserDetailActivity.this, userIc, mAlbumFiles.get(0).getPath(), R.drawable.ic_user_default);
                        String path = mAlbumFiles.get(0).getPath();
                        String avatorPath = Constant.PIC_CACHE_FILE;
                        String finishPath = avatorPath + System.currentTimeMillis() + ".jpg";
                        ImageHandle.getimage(path, finishPath, avatorPath);
                        showProgressDialog();
                        presenter.uploadImage(finishPath);
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(int requestCode, @NonNull String result) {
                        //取消
                    }
                })
                .start();
    }

    /**
     * 图片上传成功
     */
    @Override
    public void uploadImageSuccess(String result) {
        userDetail.setPortrait(result);
        UserInfoManager.getInstance().setUserInfo(new Gson().toJson(userInfo));
        GlideUtil.getInstance().loadCircleImage(this, userIc, AppUrl.getImageUrl(result), R.drawable.ic_user_default);
        presenter.setUserHeadId(result);
    }

    /**
     * 图片上传失败
     */
    @Override
    public void uploadImageFailed() {
        dismissProgressDialog();
        ToastUtil.showErrorToast(this, "上传失败");
    }

    /**
     * 更新头像资源id成功
     */
    @Override
    public void setUserHeadIdSuccess() {
        dismissProgressDialog();
        ToastUtil.showSuccessToast(this, "上传成功");
        EventBus.getDefault().post(new EventBussMessage(Constant.UPLOAD_USER_HEAD_SUCCESS_CODE, Constant.UPLOAD_USER_HEAD_SUCCESS_MESSAGE));
    }

    /**
     * 更新头像资源id失败
     */
    @Override
    public void setUserHeadIdFailed() {
        dismissProgressDialog();
        ToastUtil.showErrorToast(this, "上传失败");
    }

    /**
     * 修改昵称成功
     */
    @Override
    public void updateNickSuccess() {
        ToastUtil.showSuccessToast(this, "修改成功");
        userDetail.setNick(nick);
        UserInfoManager.getInstance().setUserInfo(new Gson().toJson(userInfo));
        userNick.setText(nick);
    }

    /**
     * 修改昵称失败
     */
    @Override
    public void updateNickFailed() {
        ToastUtil.showErrorToast(this, "修改失败");
    }

    /**
     * 完善推荐人信息成功
     */
    @Override
    public void sendRecommendUserInfoSuccess() {
        dismissProgressDialog();
    }

    /**
     * 完善推荐人信息失败
     */
    @Override
    public void sendRecommendUserInfoFailed() {
        dismissProgressDialog();
    }

}
